<template>
    <el-col>
        <div style="float:left" class="head">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item>
                    <el-input placeholder="请输入名称" v-model="select"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="SelectName()">搜索</el-button>
                    <router-link to="/home/addGoods">
                        <el-button type="primary" icon="el-icon-search">
                            添加
                        </el-button>
                    </router-link>
                </el-form-item>
            </el-form>
        </div>
        <div style="float:left">
            <el-dropdown trigger="click">
                <el-avatar :src="avatarUrl"></el-avatar>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
                    <el-dropdown-item @click.native="triggerFileInput">更gfdgdfgf换头像</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>

            <!-- 隐藏的文件输入 -->
            <input type="file" ref="fileInput" accept="image/png, image/jpeg" @change="handleFileChange"
                style="display: none" />

        </div>
    </el-col>

</template>
<script>
import { mapState, mapMutations } from 'vuex';

import { upload } from '@/api/common/common';
export default {
    data() {
        return {
            select: ' '
        }
    },
    computed: {
        ...mapState('user', ['avatarUrl']) // 从 Vuex 获取头像地址
    },

    methods: {
        DropLogin(a) {
            this.$router.replace({ path: '/' })
        },
        SelectName() {
            console.log('select' + this.select);
            if (this.select.length > 1) {
                this.$store.state.Goods.array = this.$store.state.Goods.tableData.filter(res => {
                    return res.id == this.select
                });
            } else if (this.select.length <= 1) {
                console.log(this.$store.state.Goods.tableData);
                this.$store.state.Goods.array = this.$store.state.Goods.tableData
            }
        },

        AddGoods() {
            this.$router.replace({ path: '/home/addGoods' })
        },
        // onFileChange(e) {
        //     const file = e.target.files[0];
        //     if (!file) {
        //         return;
        //     }
        //     const reader = new FileReader();
        //     reader.onload = (file) => {
        //         console.log("开始上传文件");
        //         upload(e)
        //     };
        //     reader.readAsDataURL(file);
        //     // 如果需要上传到服务器，可以在reader.onload之后添加上传代码
        // },

        // onFileChange(e) {
        //     const file = e.target.files[0];
        //     console.log('文件选择框 change 事件触发，选择的文件:', file);
        //     if (!file) {
        //         return;
        //     }
        //     const reader = new FileReader();
        //     reader.onload = () => {
        //         console.log("开始上传文件");
        //         upload(file).then((response) => {
        //             console.log('文件上传成功', response);
        //         }).catch((error) => {
        //             console.log('文件上传失败', error);
        //         });
        //     };
        //     reader.readAsDataURL(file);
        // }
        ...mapMutations('user', ['SET_AVATAR']), // Vuex mutation

        // 触发文件选择
        triggerFileInput() {
            this.$refs.fileInput.click();
        },

        // 处理文件选择
        async handleFileChange(e) {
            console.log("amizimaizmaimaizamiaamzi");

            const file = e.target.files[0];
            if (!file) return;

            // 验证文件类型和大小
            if (!this.validateFile(file)) return;

            try {
                // 显示加载状态
                const loading = this.$loading({
                    lock: true,
                    text: '上传中...',
                    spinner: 'el-icon-loading'
                });

                // 执行上传
                const res = await upload(file);

                // 更新头像地址
                this.SET_AVATAR(res.data.url);

                this.$message.success('头像更新成功');
                loading.close();
            } catch (error) {
                this.$message.error(`上传失败: ${error.message}`);
                loading.close();
            } finally {
                // 清空输入框以便重复上传
                e.target.value = '';
            }
        },

        // 文件验证
        validateFile(file) {
            const validTypes = ['image/jpeg', 'image/png'];
            const maxSizeMB = 2;

            if (!validTypes.includes(file.type)) {
                this.$message.error('仅支持 JPG/PNG 格式');
                return false;
            }

            if (file.size > maxSizeMB * 1024 * 1024) {
                this.$message.error(`文件大小不能超过 ${maxSizeMB}MB`);
                return false;
            }

            return true;
        },
    },
}
</script>

<style scoped>
.el-avatar--icon {
    font-size: 18px;
    margin-left: 750px;
}

.head {
    margin-left: 160px;
}
</style>
